﻿using System;
using System.Configuration;
using System.Web;
using System.Threading;
using System.Security.Permissions;
using System.Collections.Specialized;
using MikeKappel.Com.Uploader;


namespace MikeKappel.Com
{
    public class UploaderModule : IHttpModule
    {
        public UploaderModule()
        {

        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
       
        public String ModuleName
        {
            get { return "UploaderModule"; }
        }

        /// <summary>
        /// In the Init function, register for HttpApplication events by adding your handlers.
        /// </summary>
        /// <param name="application"></param>
        public void Init(HttpApplication application)
        {
            application.BeginRequest += (new EventHandler(Application_BeginRequest));
            application.AuthenticateRequest += new EventHandler(Application_AuthenticateRequest);
        }

        /// <summary>
        /// Your BeginRequest event handler. 
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void Application_BeginRequest(Object sender, EventArgs e)
        {
            string[] resourceNames = this.GetType().Assembly.GetManifestResourceNames();
        }
        private static void upload(Object AppAndWorker)
        {
            HttpApplication application = (HttpApplication)((Object[])AppAndWorker)[0];
            HttpWorkerRequest worker = (HttpWorkerRequest)((Object[])AppAndWorker)[1];

        
        }
        /// <summary>
        /// Your AuthenticateRequest event handler. 
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpWorkerRequest worker = GetCurrentWorkerRequest(application);

            if (!application.Request.FilePath.Contains(Core.BasePage))
                return;

            if (application.Request.QueryString[Core.ImageKey] == null)
                application.Response.Write(Core.ImageKey + " not found");

            UploaderInfo uploader = Core.GetUploader(new Guid(application.Request.QueryString[Core.ImageKey]));

            if (uploader == null)
                application.Response.Write(application.Request.QueryString[Core.ImageKey] + " not found"); 
   
            String command = application.Request.QueryString[Core.CommandKey];
            application.Response.Buffer = true;
            application.Response.Clear();
            application.Response.StatusCode = 200;
            application.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            if (!String.IsNullOrEmpty(command))
                if (command == "progress")
                    application.Response.Write((uploader.Progress.HasValue) ? uploader.Progress.Value.ToString() : "false");
                else if (command == "cancel")
                {
                    uploader.Progress = null;
                    application.Response.Write(uploader.TextForCancelled);
                }
                else if (command == "thumbnail")
                    Core.GenerateThumbnail(application.Response, uploader);
                else if (command == "original")
                    Core.Download(application.Response, uploader);
                else
                    application.Response.Write(Core.GetHtmlPageUploadForm(uploader));
            else 
                if (worker.HasEntityBody())
                    if (worker.GetTotalEntityBodyLength() > uploader.MaxSize)
                        application.Response.Write(Core.GetHtmlPageUploadFormError(uploader, Core.FormErrorTypes.Oversize, Helper.BytesToMegaBytes(uploader.MaxSize.Value).ToString()));
                    else
                        application.Response.Write(Core.SaveImageToMemory(application.Request, application.Response, worker, uploader));
            
            application.Response.End();
        }
        public void Dispose()
        {

        }

        [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
        internal static HttpWorkerRequest GetCurrentWorkerRequest(HttpApplication app)
        {
            IServiceProvider provider = (IServiceProvider)app.Context;
            if (provider == null)
                return null;

            HttpWorkerRequest worker = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
            return worker;
        }
    }
}